import axios, { AxiosInstance } from 'axios'
import { storage } from '@/store/sessionStorage'
import { CxlMessage } from '@/components/message'
import router from '@/router'

export class Http {
    //定义不需要携带token访问的接口
    notToken: string[] = [
        '/api/system/portal/login/submit',
        '/api/system/announcement/portal/release',
        '/api/system/announcement/portal/release/{id}'
    ]
    //需要formdata格式的接口
    formDataPort: string[] = [
        '/api/system/file/upload',
        '/api/report/vehicleLicense/front/result',
        '/api/report/vehicleLicense/front/result/str',
        '/api/system/portal/register/businessLicense/result/str'
    ]
    systemToken = ''
    //从启动的环境拉取访问的地址
    url = import.meta.env.VITE_HOST
    //请求携带的token
    token = ''
    //是否刷新token
    isRefreshToken = false
    //多个接口报同一个错误，只提示一次
    hint = true
    //初始化axios
    instance: AxiosInstance = axios.create({
        baseURL: this.url,
        timeout: 10000
    })
    constructor() {
        this.instance.defaults.headers.post['Content-Type'] = 'application/json'
        this.instance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
        /**
         * 添加请求拦截器
         */
        this.instance.interceptors.request.use(
            (config: any) => {
                /**
                 * 请求前判断 token 是否为空
                 * 若为空，则从本地storage拉去token
                 */
                if (this.token === '') {
                    this.token = storage.get('token')
                }

                this.isRefreshToken = false

                this.hint = true

                console.log(config.url)

                //在发送请求之前，判断接口是不是需要携带token
                if (this.notToken.includes(config.url)) {
                    //移除 Authorization 请求头
                    delete config.headers.Authorization
                    this.token = ''
                } else {
                    if (this.formDataPort.includes(config.url)) {
                        //form-data格式
                        config.headers['Content-Type'] = 'amultipart/form-data'
                    }

                    //监听请求路径是否是刷新token
                    if (config.url == '/api/system/portal/login/refreshToken') {
                        this.isRefreshToken = true
                        config.headers.Authorization = 'Bearer ' + storage.get('refreshToken')
                        console.log('refreshToken')
                    } else {
                        config.headers.Authorization = 'Bearer ' + this.token

                        //创建订单接口
                        if (config.url == '/api/mall/portal/report/order/create/store') {
                            config.headers.systemToken = storage.get('systemToken')
                        } else {
                            //移除 systemToken 请求头
                            delete config.headers.systemToken
                        }
                    }
                }

                return config
            },
            function (error) {
                // 对请求错误做些什么
                return Promise.reject(error)
            }
        )

        /**
         * 添加响应拦截器
         */
        this.instance.interceptors.response.use(
            response => {
                // 2xx 范围内的状态码都会触发该函数。
                // console.log('url:', response.config.url)
                // console.log( `${response.config.method === 'get' ? 'get:' : 'data:'}`, response.config.method === 'get' ? response.config.params : response.config.data)
                console.log('%cresult:', 'color:#000;font-size:16px;background:#ebebeb;padding:0 4px', response.data)

                let result: any = {
                    data: undefined
                }

                // 对响应数据做点什么
                if (response.data.value === 200) {
                    result = response
                    //是刷新token请求，则清楚本地token
                    if (this.isRefreshToken) {
                        storage.remove('token')
                        this.isRefreshToken = false
                        this.token = ''
                    }
                    return result
                } else if (response.data.value === 30012) {
                    //token 无效
                    router.replace('/login')
                    console.log('token 无效')
                    sessionStorage.clear()
                    return {
                        data: {
                            value: 0
                        }
                    }
                } else {
                    // ElMessage.error(response.data.desc)
                    // alert(response.data.desc)
                    return response
                }
            },
            error => {
                // 超出 2xx 范围的状态码都会触发该函数。
                // alert(error.response)
                console.log('error', error, error.response?.data.value)

                //对错误提示进行弹窗提示
                let { message } = error
                if (message === 'Network Error') {
                    message = '后端接口连接异常'
                    CxlMessage.error(message)
                } else if (message.includes('timeout')) {
                    message = '系统接口请求超时'
                    CxlMessage.error(message)
                } else if (message.includes('Request failed with status code')) {
                    const code = message.substr(message.length - 3)
                    message = '系统接口' + code + '异常'
                    if ([30012, 30011].includes(error.response?.data.value)) {
                        console.log('重新登录')
                        const timer = storage.get('loginCountDownTimer')
                        if (this.hint) {
                            CxlMessage.error('登录数据失效，请重新登录！')
                            this.hint = false
                            router.replace('/login')
                            clearInterval(timer)
                            storage.clear()
                        }
                    } else if (error.response?.data.value === 30016) {
                        //用户已在其它设备登录
                        const timer = storage.get('loginCountDownTimer')
                        if (this.hint) {
                            console.log('用户已在其它设备登录router', router)
                            CxlMessage.error(error.response?.data.desc)
                            this.hint = false
                            router.replace('/login')
                            clearInterval(timer)
                            storage.clear()
                        }
                    } else if (error.response?.data.value === 30002) {
                        CxlMessage.error('没有权限！')
                    } else {
                        CxlMessage.error(
                            '错误码：' + (error.response?.data.value || error.response?.data.status) + '，请联系客服！'
                        )
                    }
                }

                // 对响应错误做点什么
                return Promise.reject(error)
            }
        )
    }
}

//默认初始化一次
export const http = new Http()

export const request = http.instance
